import {
  _decorator,
  AudioClip,
  AudioSource,
  Component,
  director,
  Node,
} from "cc";
import Singleton from "../base/Singleton";
const { ccclass, property } = _decorator;

@ccclass("AudioMgr")
export class AudioMgr extends Singleton {
  private _audioSource: AudioSource;

  static get Instance(): AudioMgr {
    return super.getInstance<AudioMgr>();
  }

  constructor() {
    super();

    const audioMgr = new Node();

    director.getScene().addChild(audioMgr);

    director.addPersistRootNode(audioMgr);

    this._audioSource = audioMgr.addComponent(AudioSource);
  }

  get audioSource() {
    return this._audioSource;
  }

  play(clip: AudioClip, volume = 1.0) {
    this._audioSource.stop();
    this._audioSource.clip = clip;
    this._audioSource.play();
    this._audioSource.volume = volume;
  }

  playOneShot(clip: AudioClip, volume = 1.0) {
    this._audioSource.playOneShot(clip, volume);
  }
}
